package jobteam.contacteventstocalendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.provider.ContactsContract.Data;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class addContactEventActivity extends Activity implements OnClickListener , OnCheckedChangeListener {
	private String TAG = "addContactEventActivity";
	private Context Context;

	private int selectId;
	private EditText eDateText;
	private DatePicker date;
	private String strYear, strMonth, strDay;
	private String strDate="";
	private String eventType;
	private boolean isEdit = false, isConfirm = false;
	private int dataID;
	private int selectLang;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main1);
		Context = this;

		Intent intent = getIntent();
		//	selectListId in hasNoEventContactList
		if(!intent.hasExtra("SelectId")){
			Log.d(TAG, "SelectId error");
			return;
		}

		date = (DatePicker)findViewById(R.id.DatePicker01);
		selectId = intent.getIntExtra("SelectId", 0);

		if(intent.getAction().equals("android.intent.action.EDIT_EVENT")){
			isEdit = true;
			Cursor dataCursor = getContentResolver().query(Data.CONTENT_URI, new String[]{
					ContactsContract.Data._ID,			// 0
					ContactsContract.Data.MIMETYPE,		// 1
					ContactsContract.Data.DATA1			// 2
			}, 
			ContactsContract.Data.RAW_CONTACT_ID + " = " + selectId, 
			null, null);
			String dateStr = null;
			if(dataCursor.moveToFirst()){
				for(int i = 0 ; i < dataCursor.getCount() ; i++){
					if(dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.MIMETYPE)).
							equals(Event.CONTENT_ITEM_TYPE)){
						dataID = dataCursor.getInt(dataCursor.getColumnIndex(ContactsContract.Data._ID));
						dateStr = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DATA1));
					}
					dataCursor.moveToNext();
				}
			}

			int strIndex = dateStr.indexOf("-", 1);
			int year, month, day;
			if(strIndex == 1)
				year = 2000;
			else
				year = Integer.parseInt(dateStr.substring(strIndex - 4, strIndex));

			month = Integer.parseInt(dateStr.substring(strIndex + 1, strIndex + 3));
			day = Integer.parseInt(dateStr.substring(strIndex + 4, strIndex + 6));

			initDate(year, month, day);

			date.init(year, month - 1, day, new DatePicker.OnDateChangedListener() {
				@Override
				public void onDateChanged(DatePicker view, int year, int monthOfYear,
						int dayOfMonth) {
					monthOfYear += 1;
					strYear = String.valueOf(year);
					strMonth = String.valueOf(monthOfYear);
					strDay = String.valueOf(dayOfMonth);
					if(strMonth.length() == 1){
						strMonth = 0 + strMonth;
					}
					if(strDay.length() == 1){
						strDay = 0 + strDay;
					}
					strDate = strYear + "-" + strMonth + "-" + strDay;
				}
			});
		}
		else{
			isEdit = false;

			initDate(date.getYear(), date.getMonth()+1 , date.getDayOfMonth());

			// DatePicker Setting
			date.init(date.getYear(), date.getMonth(), date.getDayOfMonth(), new DatePicker.OnDateChangedListener() {

				@Override
				public void onDateChanged(DatePicker view, int year, int monthOfYear,
						int dayOfMonth) {
					Log.d(TAG, "onDateChanged");

					monthOfYear += 1;

					strYear = String.valueOf(year);
					strMonth = String.valueOf(monthOfYear);
					strDay = String.valueOf(dayOfMonth);

					if(strMonth.length() == 1){
						strMonth = 0 + strMonth;
					}

					if(strDay.length() == 1){
						strDay = 0 + strDay;
					}
					strDate = strYear + "-" + strMonth + "-" + strDay;
				}
			});
		}

		eDateText = ((EditText)((LinearLayout)( (LinearLayout)date.getChildAt(0) ).getChildAt(2)).getChildAt(1));
		eDateText.addTextChangedListener(new myWatcher());
		selectLang = eDateText.getSelectionEnd();

		((Button)findViewById(R.id.btnOk)).setOnClickListener(this);
		((Button)findViewById(R.id.btnCancel)).setOnClickListener(this);
		((RadioGroup)findViewById(R.id.radiogroupId)).setOnCheckedChangeListener(this);
	}

	@Override
	public void onClick(View v) {

		switch(v.getId()) {
		case R.id.btnOk :
			if(strDate.length() == 0){
				Toast.makeText(this, "Check Date", Toast.LENGTH_LONG).show();
				return;
			}

			new AlertDialog.Builder(this)
			.setTitle("Notify")
			.setMessage(getResources().getText(R.string.Are_you_sure) + "? (" + strDate + ")")
			.setIcon(R.drawable.icon)
			.setCancelable(false)
			.setPositiveButton(R.string.Confirm, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int whichButton){
					if(isEdit){
						Uri updateUri = ContentUris.withAppendedId(Data.CONTENT_URI, dataID);
						ContentValues contentValue = new ContentValues();
						contentValue.put(Data.DATA1, strDate);
						contentValue.put(Data.DATA2, eventType);
						getContentResolver().update(updateUri, contentValue, null, null);
						Toast.makeText(Context, R.string.Edit_complete, Toast.LENGTH_SHORT).show();
					}
					else{
						ContentValues contentValue = new ContentValues();
						contentValue.put(Data.MIMETYPE, Event.CONTENT_ITEM_TYPE);
						contentValue.put(Data.RAW_CONTACT_ID, selectId);
						contentValue.put(Data.DATA1, strDate);
						contentValue.put(Data.DATA2, eventType);
						Context.getContentResolver().insert(Data.CONTENT_URI, contentValue);
						Toast.makeText(Context, R.string.Insert_complete, Toast.LENGTH_SHORT).show();
					}
					isConfirm = true;
					finish();
				}
			}).setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					return;
				}
			}).show();

			break;
		case R.id.btnCancel :
			finish();
			break;
		}
	}

	@Override
	protected void onDestroy() {
		if(!isConfirm)
			Toast.makeText(this, R.string.Cancel, Toast.LENGTH_SHORT).show();
		super.onDestroy();
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch(checkedId) {
		case R.id.radAnniversary :
			eventType = "1";
			Log.d(TAG, "onCheckedChanged_radAnniversary");
			break;
		case R.id.radBirthday :
			eventType = "3";
			Log.d(TAG, "onCheckedChanged_radBirthday");
			break;
		case R.id.radEvent :
			eventType = "2";
			Log.d(TAG, "onCheckedChanged_radEvent");
			break;
		}
	}

	public void initDate(int aYear, int aMonth, int aDay){
		strYear = String.valueOf(aYear);
		strMonth = String.valueOf(aMonth);
		strDay = String.valueOf(aDay);

		if(strMonth.length() == 1){
			strMonth = 0 + strMonth;
		}

		if(strDay.length() == 1){
			strDay = 0 + strDay;
		}
		strDate = strYear + "-" + strMonth + "-" + strDay;
	}

	class myWatcher implements TextWatcher {
		public myWatcher(){}
		@Override
		public void afterTextChanged(Editable s) {}
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,	int after) {}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			String tmpDay = ((EditText)((LinearLayout)( (LinearLayout)date.getChildAt(0) ).getChildAt(2))
					.getChildAt(1)).getText().toString();
			if(selectLang == 4){
				strYear = tmpDay;
			}else if(selectLang == 2){
				strDay = tmpDay;
			}
			if(strDay.length() == 1){
				strDay = 0 + strDay;
			}
			Log.d(TAG, strDate);
			strDate = strYear + "-" + strMonth + "-" + strDay;
		}
	}
}

